package com.controller;


import com.orm.ServiceCalledEntity;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by lirance on 16/5/10.
 */
public class AverageRtt {

    static List<SavedSCRtt> aveRtt = new ArrayList<>();

    public static void main(String[] args) throws Exception {

        List userlist = new GetUsersList().GetUserLists();
        List servicelist = new GetServiceList().GetServiceLists();

        int unum = userlist.size();
        int snum = servicelist.size();
        for (int i = 1; i <= unum; i++) {
            for (int j = 1; j <= snum; j++) {
                SavedSCRtt savedSCRtt = new SavedSCRtt();
                savedSCRtt.setUid(i);
                savedSCRtt.setWsid(j);
                savedSCRtt.setAveRtt(saveaverage(i, j));
                aveRtt.add(savedSCRtt);
            }
        }


        File fileout = new File("./src/com/controller/averageRtt.txt");

//        Iterator iterator = aveRtt.iterator();
        FileWriter fw = null;
        int num = aveRtt.size(),i=0;
        BufferedWriter writer = null;
        try {
            fw = new FileWriter(fileout);
            writer = new BufferedWriter(fw);
            while (i<num) {
                writer.write(aveRtt.get(i).getUid()+"\t"+aveRtt.get(i).getWsid()+"\t"+aveRtt.get(i).getAveRtt());
                writer.newLine();//换行
                i++;
            }
            writer.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                writer.close();
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }

    private static Double saveaverage(int uid, int wsid) throws Exception {
        double average, sum = 0.00, frq = 0;
        List<ServiceCalledEntity> sc = (new GetServiceCallList()).GetServiceCallListsByusId(uid, wsid);
        for (int i = 0; i < sc.size(); i++) {
            sum += sc.get(i).getRtt() * sc.get(i).getFrequency();
            frq += sc.get(i).getFrequency();
        }
        average = sum * 1.000 / frq;
        return average;
    }
}
